package com.xinguan.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinguan.entity.TbUser;
import com.xinguan.service.TbUserService;
import com.xinguan.utils.JWTUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 郭经伟
 * @Date 2021/7/10
 * 用户域
 **/
@Component("realm")
public class UserRealm extends AuthorizingRealm {


    @Resource
    private TbUserService userService;

    /**
     * 大坑 必须重写这个方法，不然shiro会报错
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 授权
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 认证
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     *
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {

        // 获得token
        String token = (String) auth.getCredentials();
        // 获得token中的username
        String username = JWTUtil.getUsername(token);

        if (username == null) {
            throw new AuthenticationException(" token 错误，请重新登入!");
        }
        TbUser tbUser = userService.getOne(new QueryWrapper<TbUser>().eq("username", username));

        if (tbUser == null) {
            throw new AccountException("账号不存在!");
        }

        if (JWTUtil.isExpire(token)) {
            throw new AuthenticationException(" token过期，请重新登入！");
        }

        if (!JWTUtil.verify(token, username, tbUser.getPassword())) {
            throw new CredentialsException("密码错误!");
        }

        if (tbUser.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定!");
        }

        // 如果验证通过 获得此用户的角色...
        return new SimpleAuthenticationInfo(tbUser, token, getName());
    }
}
